import { Body, Controller, Get, Param, Post, UseGuards, Headers } from '@nestjs/common';
import { UserAccountRegisterDto, UserAccountDto, UserUpdateDto } from './dto/user.dto';
import { UserService } from './user.service';
import { AuthService } from 'src/services/Auth';
import { getResponse, ERROR_CODE, ERROR_MESSAGE } from 'src/common/const/const';
import { generateUniqueUserId } from 'src/common/utils/uuid';
// @UseGuards(RolesGuard)
@Controller('user')
export class UserController {
  constructor(
    private readonly userService: UserService,
    private readonly authService: AuthService
  ) { }

  @Post('/create')
  // @Roles('admin')
  async create(@Body() userAccountRegisterDto: UserAccountRegisterDto) {
    // 默认分配一个唯一用户Id
    const uniqueUserId = generateUniqueUserId();
    let response = await this.userService.createUser({ userid: uniqueUserId, avatar: "", ...userAccountRegisterDto });
    let result = {
      code: 0,
      data: response,
      msg: "success"
    }
    return result;
  }

  @Get('/find')
  // @Roles('admin')
  async find(@Headers() headers: any) {
    const userInfo = this.authService.checkAuth(headers);
    if (!userInfo) {
      return getResponse(ERROR_CODE.VERIFY_EXPIRE, ERROR_MESSAGE[ERROR_CODE.VERIFY_EXPIRE], {})
    }

    let response = await this.userService.findUser(userInfo.userid);
    let result = {
      code: 0,
      data: response,
      msg: "success"
    }
    return result;
  }

  @Post('/update')
  async update(@Body() userUpdateDto: UserUpdateDto, @Headers() headers: any) {
    const userInfo = this.authService.checkAuth(headers);
    if (!userInfo) {
      return getResponse(ERROR_CODE.VERIFY_EXPIRE, ERROR_MESSAGE[ERROR_CODE.VERIFY_EXPIRE], {})
    }

    let response = await this.userService.updateUser({ userid: userInfo.userid, ...userUpdateDto });
    if (response.affected === 0) {
      return getResponse(ERROR_CODE.UPDATE_FAIL, ERROR_MESSAGE[ERROR_CODE.UPDATE_FAIL], {})
    }
    // 更新成功则返回成功数据
    let findResponse = await this.userService.findUser(userInfo.userid);
    let result = {
      code: 0,
      data: findResponse,
      msg: "success"
    }
    return result;
  }

}
